<template>
  <div class="app-container">
    <ListTab v-model="activeId" :tabs="tabsList" :show-header="!showMobilePage" is-table @tabClick="statusTabChange" />
    <div class="invoice">
      <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
        <DataDisplay :data-list="statisticsList" class="mb16"/>
        <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <div class="opeator-bar">
            <btnGroup
              v-if="hasRouteAuth('crm:receipt:export')"
              ref="btnGroupRef"
              :list="[
                {label:'导出',exportApi:'/admin/invoice/list/export', exportName:'销项发票列表', beforeExport: exportBeforeExport, type: 'export'},
              ]"
            />
          </div>
        </div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length > 0"
            ref="invoiceTableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="49"
            :border="true"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            hightlight-current-row
            header-cell-class-name="order-data-header-cell"
            fit
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column align="center" type="selection" fixed="left" width="50"/>
            <u-table-column align="left" label="发票号码" min-width="130">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.number" :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.number }}</div>
                  <div class="ellipsisOne" style="color: #406eff; cursor: pointer;" @click="toDetail(scope.row)">
                    {{ scope.row.number }}
                  </div>
                </el-tooltip>
                <div v-else >--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="发票类型" width="174px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceType" placement="top-start"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="纳税人名称" width="286px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.taxpayerName" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="我方抬头" width="286px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.ourTitle" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人" min-width="110">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="right" label="含税金额(元)" min-width="130" prop="amount" sortable="custom">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="开票项目" width="230px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.project" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="开票审批" min-width="140">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.approvalNo" :open-delay="800">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.approvalNo }}</div>
                  <div class="ellipsisOne" style="color: #406eff; cursor: pointer;" @click="goIssueInvoiceDetail(scope.row)">
                    {{ scope.row.approvalNo }}
                  </div>
                </el-tooltip>
                <div v-else >--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="发票状态" min-width="110">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.invoiceState || scope.row.invoiceState === 0" :open-delay="800">
                  <div slot="content">{{ scope.row.invoiceState | invoiceState }}</div>
                  <div style="display:flex;align-items:center">
                    <div :class="`color-state-${scope.row.invoiceState}`" class="dot"/>
                    <div>{{ scope.row.invoiceState | invoiceState }}</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态" min-width="110">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status || scope.row.status === 0" :open-delay="800">
                  <div slot="content">{{ scope.row.status | invoiceStatus }}</div>
                  <div style="display:flex;align-items:center">
                    <div :class="`color-${scope.row.status}`" class="dot"/>
                    <div>{{ scope.row.status | invoiceStatus }}</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请部门" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.applyDepartment" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="开票人" min-width="110">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.issuer" :label="scope.row.issuer" :user-id="scope.row.issuerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.department" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="开票日期" min-width="160" prop="invoiceDate" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceDate | format('YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column fixed="right" align="left" width="50" label="操作">
              <template slot-scope="scope">
                <div class="button-text" @click="toDetail(scope.row)">查看</div>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="[
                {label:'导出',exportApi:'/admin/invoice/list/export', exportName:'销项发票列表', isBeforeExport: true, beforeExport: exportBeforeExport, type: 'export', refName: 'invoiceExportRef' },
              ]"
              show-mobile-icon
            />
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ListTab from '@/components/ListTab';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { getInvoiceTypes, getInvoiceList, getInvoiceProjectList, getOurTitleList, getInvoiceStatistics } from '@/api/invoice';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { tabList } from '@/api/invoice';
import { hasRouteAuth } from '@/utils/permission';
import { format } from '@/filters/date';
import { getDepartmentAll } from '@/api/config';
// 跨页选中逻辑
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import tableSelections from '@/mixins/tableSelections';
import icon_26 from '@/assets/dataDisplay/icon_26.png';
import icon_27 from '@/assets/dataDisplay/icon_27.png';
import icon_28 from '@/assets/dataDisplay/icon_28.png';

export default {
  name: 'Invoice',
  filters: {
    format,
    invoiceStatus(status) {
      return {
        0: '执行中',
        1: '已完成',
        2: '作废中',
        3: '已作废'
      }[status] || '--';
    },
    invoiceState(status) {
      return {
        0: '正数正常',
        1: '正数作废',
        2: '负数正常',
        3: '负数作废'
      }[status] || '--';
    }
  },
  components: {
    EmptyPlaceholder,
    ListTab,
    btnGroup,
    DataDisplay,
    MoreOpeator
  },
  mixins: [TableAdaptive, tableSelections, mobileTable],
  data() {
    return {
      statisticsData: {
        invoiceAmount: null,
        relatedOrderAmount: null,
        relatedFlowAmount: null
      },
      isUmyTable: true,
      invoiceTypes: [],
      invoiceProjectList: [],
      tabsList: [],
      deptTreeList: [],
      ourTitleList: [],
      perPage: 20,
      listLoading: true,
      page: 1,
      activeId: -1,
      paramsObj: {},
      sortName: '',
      sortType: '',
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      tableRefName: 'invoiceTableRef', // 表格的ref名称
      idKey: 'id' // 唯一表示字段
    };
  },
  computed: {
    statisticsList() {
      const { invoiceAmount, relatedOrderAmount, relatedFlowAmount } = this.statisticsData;
      return [
        { data: (invoiceAmount / 100).toFixed(2), label: '含税金额', icon: icon_26 },
        { data: (relatedOrderAmount / 100).toFixed(2), label: '关联订单金额', icon: icon_27 },
        { data: (relatedFlowAmount / 100).toFixed(2), label: '关联流水金额', icon: icon_28 }
      ];
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'number', name: '发票号码', inputType: 'number', labelWidth: '70px', type: 'input' },
        { keyword: 'taxpayerName', name: '纳税人名称', labelWidth: '100px', type: 'input' },
        { keyword: 'proposer', name: '申请人', labelWidth: '70px', type: 'input' },
        { keyword: 'amount', name: '含税金额', labelWidth: '100px', type: 'inputRange' },
        { keyword: 'approvalNo', name: '开票审批', labelWidth: '70px', type: 'input' },
        { keyword: 'issuer', name: '开票人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'invoiceType', name: '发票类型', valueName: 'label', type: 'select', options: this.invoiceTypes },
        { keyword: 'project', name: '开票项目', valueName: 'label', type: 'select', options: this.invoiceProjectList },
        { keyword: 'ourTitle', name: '我方抬头', valueName: 'label', type: 'select', options: this.ourTitleList },
        { keyword: 'applyDepartment', name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'department', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'invoiceState', name: '发票状态', type: 'select', options: [
          { value: 0, label: '正数正常' },
          { value: 1, label: '正数作废' },
          { value: 2, label: '负数正常' },
          { value: 3, label: '负数作废' }
        ] },
        // 日期
        { keyword: 'invoiceDate', name: '开票日期', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'invoiceDate', start: 'invoiceDateStart', end: 'invoiceDateTimeEnd', type: 'time' },
        { attr: 'amount', start: 'amountStart', end: 'amountEnd', type: 'number' }
      ];
    },
    arrayKeyArr() {
      return ['applyDepartment', 'department'];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 246;
    }
  },
  created() {
    this.fetchData(true);
    this.queryInvoiceTypes();
    this.queryInvoiceProjectList();
    this.queryDeptTreeList();
    this.queryOurTitleList();
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isChange = from.name === 'invoiceDetail';
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      this.fetchData(true);
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
    if (this.list.isInit) {
      this.queryInvoiceTypes();
      this.queryInvoiceProjectList();
      this.queryDeptTreeList();
      this.queryOurTitleList();
    }
  },
  methods: {
    hasRouteAuth,
    // tab列表
    queryTabList() {
      const params = this.formatParams();
      delete params.tabStatus;
      tabList(params).then(res => {
        if (res.code === 200) {
          this.tabsList = res.data;
        }
      });
    },
    // 部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    // 发票类型
    queryInvoiceTypes() {
      getInvoiceTypes({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '发票类型'
            });
          });
          this.invoiceTypes = result;
        }
      });
    },
    // 开票项目
    queryInvoiceProjectList() {
      getInvoiceProjectList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '开票项目'
            });
          });
          this.invoiceProjectList = result;
        }
      });
    },
    // 我方抬头
    queryOurTitleList() {
      getOurTitleList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '我方抬头'
            });
          });
          this.ourTitleList = result;
        }
      });
    },
    toDetail(rowData) {
      this.$router.push({
        name: 'invoiceDetail',
        params: { id: rowData.id }
      });
    },
    goIssueInvoiceDetail(rowData) {
      const { applyId, processId } = rowData;
      const url = this.$router.resolve({
        name: 'issueInvoiceDetail',
        query: {
          issueId: applyId,
          processId: processId
        }
      });
      window.open(url.href, '_blank');
    },
    // 表格tab切换按钮
    statusTabChange() {
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      this.listLoading = true;
      const params = this.formatParams();
      this.queryTabList();
      this.getInvoiceStatistics(params);
      getInvoiceList(params).then(res => {
        if (res.code === 200) {
          this.list = res.data;
          this.setSelectRow && this.setSelectRow(res.data.items);
        }
        this.list.isInit = false;
        this.listLoading = false;
      }).catch(() => {
        this.listLoading = false;
      });
    },
    getInvoiceStatistics(params) {
      getInvoiceStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
      }).catch(err => console.error(err.message));
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.tabStatus = this.activeId;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(item => item.id).join();
      }
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'invoiceExportRef');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FD8546 0, #31CC9C 1, #FF4E5F 2, #999 3;
$state: #31CC9C 0, #999 1, #31CC9C 2, #999 3;
.invoice {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .opeator-bar {
      position: absolute;
      right: 0;
      top: 0;
      display: flex;
      align-items: center;
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
    @each $c, $i in $bgc {
      &.color-#{$i} {
        background: $c;
      }
    }
    @each $c, $i in $state {
      &.color-state-#{$i} {
        background: $c;
      }
    }
  }
}
</style>
